#!/bin/sh
### BEGIN INIT INFO
# Provides:          app
# Required-Start:    $lcd.sh $fpga.sh
# Required-Stop:
# Default-Start:     S
# Default-Stop:      S
### END INIT INFO

LCD=/home/root/bin/lcd.sh

APP_DIR="/home/root"
PID_FILE="/home/root/app.pid"
APP="$APP_DIR/bin/app"
cd $APP_DIR

start_app() {
    echo -n "Starting App"
    $LCD print1 "Starting App"
    chmod +x $APP
    start-stop-daemon --start --quiet --background --exec $APP
    echo "."
    $LCD print2 "Finished"
}

stop_app() {
    echo -n "Stopping App"
    $LCD print1 "Stopping App"
    start-stop-daemon --stop --quiet --exec $APP
    echo "."
    $LCD print2 "Finished"
}

upgrade() {
    $LCD print1 "[APP Upgrade Program]"
    $LCD print2 "Extracting..."

    tar -xzf $1 -C "$APP_DIR"
    sync

    $LCD print2 "Rebooting..."

    sync
    reboot
}

case "$1" in
  start)
    start_app
    ;;
  stop)
    stop_app
    ;;
  restart)
    stop_app
    echo -n "Waiting for App to die off"
    $LCD print1 "Waiting for App to die off"
    $LCD print2 "."
    for i in 1 2 3 ;
    do
        sleep 1
        echo -n "."
        $LCD append "."
    done
    echo ""
    $LCD append "Done."
    start_app
    ;;
  upgrade)
    upgrade $2
    ;;
  *)
    echo "Usage: /etc/init.d/app {start|stop|reload|restart|upgrade *.upgrade}"
    exit 1
esac

exit 0
